//
// Created by sai on 2019/4/7.
//

#include "PolynomialOperator.h"

PolyList makeEmpty(PolyList list, char *name) {
    list = malloc(sizeof(struct PolyList));
    list->head = malloc(sizeof(struct Node));
    list->head->next = NULL;
    list->last = NULL;
    list->name = name;
    list->Len = 0;
    return list;
}

bool IsEmpty(PolyList list) {
    return list->head->next == NULL;
}

bool IsLast(Position pos) {
    return pos->next == NULL;
}

Position FindNode(Type data, PolyList list) {
    Position pos;
    pos = list->head->next;
    while (pos != NULL && pos->data.Exponent != data.Exponent)
        pos = pos->next;
    return pos;
}

Position FindNodePrev(Type data, PolyList list) {
    Position pos;
    pos = list->head->next;
    while (pos != NULL && pos->next->data.Exponent != data.Exponent)
        pos = pos->next;
    return pos;
}

bool InsertNode(Type data, PolyList list, Position pos) {
    Position newNode;
    newNode = malloc(sizeof(struct Node));
    if (newNode == NULL)
        return false;
    newNode->data = data;
    newNode->next = pos->next;
    pos->next = newNode;
    return true;
}

bool DeleteNode(Type data, PolyList list) {
    Position nodePrev, TmpNode;
    nodePrev = FindNodePrev(data, list);
    if (nodePrev == NULL)
        return false;
    TmpNode = nodePrev->next;
    nodePrev->next = TmpNode->next;
    free(TmpNode);
    return true;
}

bool DeleteList(PolyList list) {
    Position pos, TmpNode;
    pos = list->head->next;
    list->head->next = NULL;
    while (pos != NULL) {
        TmpNode = pos->next;
        free(pos);
        pos = TmpNode;
    }
}

void Append(Type data, PolyList list) {
    Position pos;
    pos = list->head;
    while (!IsLast(pos))
        pos = pos->next;
    if (!InsertNode(data, list, pos))
        puts("Insert failed");
}

void InputPolynomialData(int Coefficient, int Exponent, PolyList list) {
    Type poly;
    poly.Coefficient = Coefficient;
    poly.Exponent = Exponent;
    Append(poly, list);
}

void PrintPolynomial(PolyList list) {
    Position pos;
    pos = list->head->next;
    printf("%s = ", list->name);
    while (pos != NULL) {
        if (pos->data.Coefficient > 0 && pos != list->head->next)
            printf(" + %d ^ %d", pos->data.Coefficient, pos->data.Exponent);
        else if (pos->data.Coefficient < 0)
            printf(" - %d ^ %d", abs(pos->data.Coefficient), pos->data.Exponent);
        else
            printf(" %d ^ %d", pos->data.Coefficient, pos->data.Exponent);
        pos=pos->next;
    }
}